package com.xdtech.hotel.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.thoughtworks.xstream.XStream;
import com.xdtech.common.utils.JsonUtil;
import com.xdtech.hotel.model.DeviceLink;
import com.xdtech.hotel.model.DeviceLinkOption;
import com.xdtech.hotel.protocol.vo.Ac;
import com.xdtech.hotel.protocol.vo.Component;
import com.xdtech.hotel.protocol.vo.Dimmer;
import com.xdtech.hotel.protocol.vo.Music;
import com.xdtech.hotel.protocol.vo.Node;
import com.xdtech.hotel.protocol.vo.Tv;
import com.xdtech.hotel.service.DeviceLinkService;
import com.xdtech.hotel.util.ComponentHandler;
import com.xdtech.hotel.util.HotelConstants;
import com.xdtech.hotel.vo.DeviceLinkItem;
import com.xdtech.web.model.Pagination;
import com.xdtech.web.model.ResultMessage;

/**
 * 
 * @author max.zheng
 * @create 2015-04-04 11:12:27
 * @since 1.0
 * @see
 */
@Controller
@Scope("prototype")
public class DeviceLinkController {
	@Autowired
	private DeviceLinkService deviceLinkService;
	@RequestMapping(value="/deviceLink.do",params = "deviceLink")
	public ModelAndView skipDeviceLink() {
		return new ModelAndView("hotel/deviceLink/deviceLink_ftl");
	}
	
	@RequestMapping(value="/deviceLink.do",params="loadList")
	@ResponseBody
	public Map<String, Object> loadList(HttpServletRequest request,Pagination pg) {
		Map<String, Object> results = null;
		if (StringUtils.isEmpty(request.getParameter("page"))) {
			//不分页处理
			results = deviceLinkService.loadPageAndCondition(null, null);
		}else {
			results = deviceLinkService.loadPageAndCondition(pg, null);
		}
		
		return results;
	}
	
	@RequestMapping(value="/deviceLink.do",params = "editDeviceLink")
	public ModelAndView editDeviceLink(HttpServletRequest request,Long deviceLinkId) {
		if (deviceLinkId!=null) {
			DeviceLinkItem deviceLinkItem = deviceLinkService.loadDeviceLinkItem(deviceLinkId);
			Component component = ComponentHandler.loadComponent(deviceLinkItem);
			request.setAttribute("component", component);
			request.setAttribute("deviceLinkItem", deviceLinkItem);
		}
		return new ModelAndView("hotel/deviceLink/editDeviceLink_ftl");
	}
	
	
	@RequestMapping(value="/deviceLink.do",params = "addDeviceLinkInConfig")
	public ModelAndView addDeviceLinkInConfig(HttpServletRequest request,Long deviceLinkId,String rowIndex) {
		if (deviceLinkId!=null) {
			DeviceLinkItem deviceLinkItem = deviceLinkService.loadDeviceLinkItem(deviceLinkId);
			Component component = ComponentHandler.loadComponent(deviceLinkItem);
			request.setAttribute("component", component);
			request.setAttribute("isAdd", "false");
			request.setAttribute("rowIndex", rowIndex);
			request.setAttribute("deviceLinkItem", deviceLinkItem);
		}else {
			request.setAttribute("isAdd", "true");
		}
		return new ModelAndView("hotel/deviceLink/addDeviceLinkInConfig_ftl");
	}
	
	@RequestMapping(value="/deviceLink.do",params = "saveDeviceLink")
	@ResponseBody
	public ResultMessage saveDeviceLink(DeviceLinkItem item) {
		ResultMessage r = new ResultMessage();
		if (deviceLinkService.saveOrUpdateDeviceLink(item)) {
			r.setSuccess(true);
		}else {
			r.setSuccess(false);
		}
		return r;
	}
	
	@RequestMapping(value="/deviceLink.do",params = "deleteDeviceLinkItems")
	@ResponseBody
	public ResultMessage deleteDeviceLinkItems(String ids) {
		ResultMessage r = new ResultMessage();
		if (StringUtils.isNotEmpty(ids)) {
			String[] tempIds = ids.split(",");
			List<Long> deviceLinkIds = new ArrayList<Long>();
			for (String id : tempIds) {
				deviceLinkIds.add(Long.valueOf(id));
			}
			deviceLinkService.deleteDeviceLinkInfo(deviceLinkIds);
			r.setSuccess(true);
		}else {
			r.setSuccess(false);
		}
		return r;
	}
	
	@RequestMapping(params = "saveDeviceOptionValues")
	@ResponseBody
	public ResultMessage saveDeviceOptionValues(String data) {
		ResultMessage r = new ResultMessage();
//		System.out.println(data);
		Map<String, Class> classMap = new HashMap<String, Class>();
		classMap.put("id", Long.class);
		classMap.put("lid", String.class);
		classMap.put("ltype", String.class);
		classMap.put("deviceLinkOptions", DeviceLinkOption.class);
		DeviceLink deviceLink = (DeviceLink) JsonUtil.getObjByJson(data, DeviceLink.class,classMap);
		deviceLinkService.saveDeviceLinkOptions(deviceLink);
		return r;
	}
	
	@RequestMapping(params = "saveDeviceLinkAndComponent")
	@ResponseBody
	public ResultMessage saveDeviceLinkAndComponent(String data) {
		ResultMessage r = new ResultMessage();
		try
		{
			System.out.println(data);
			JSONObject jsonObject = new JSONObject(data);
			DeviceLink deviceLink = new DeviceLink();
			String id = jsonObject.getString("id");
			if (StringUtils.isBlank(id))
			{
				deviceLink.setId(null);
			}else
			{
				deviceLink.setId(Long.valueOf(id));
			}
			
			deviceLink.setLid(jsonObject.getString("lid"));
			String ltype = jsonObject.getString("ltype");
			deviceLink.setLtype(ltype);
			deviceLink.setChannel(jsonObject.getString("channel"));
			deviceLink.setAddr(jsonObject.getString("addr"));
			//根据类型创建不同元件信息
			Component component = null;
			JSONObject componentJson = jsonObject.getJSONObject("component");
			if (HotelConstants.COMPONENT_MUSIC.equals(ltype))
			{
				//(String addr, String channel, String power, String volume,
//				String ch, String item)
				//音乐
				component = new Music(componentJson.getString("addr"),componentJson.getString("channel"),componentJson.getString("power"),componentJson.getString("volume"),componentJson.getString("input"),componentJson.getString("ch"),componentJson.getString("item"));
			} else if (HotelConstants.COMPONENT_TV.equals(ltype))
			{
				//电视
				component = new Tv(componentJson.getString("addr"),componentJson.getString("channel"),componentJson.getString("power"),componentJson.getString("volume"),componentJson.getString("input"),componentJson.getString("ch"),componentJson.getString("item"));
			} else if (HotelConstants.COMPONENT_AC.equals(ltype))
			{
				//空调
				component = new Ac(componentJson.getString("addr"),componentJson.getString("channel"),componentJson.getString("power"),componentJson.getString("mode"),componentJson.getString("fan"),componentJson.getString("temp"));
			} else if (HotelConstants.COMPONENT_DIMMER.equals(ltype))
			{
				//调灯
				component = new Dimmer(componentJson.getString("addr"),componentJson.getString("channel"),componentJson.getString("status"),componentJson.getString("freq"),componentJson.getString("delay"),componentJson.getString("value"));
			}else if (HotelConstants.COMPONENT_NODE.equals(ltype))
			{
				//灯光
				component = new Node(componentJson.getString("type"),componentJson.getString("addr"),componentJson.getString("channel"),componentJson.getString("status"),componentJson.getString("freq"),componentJson.getString("delay"));
			}
			deviceLink.setComponent(new XStream().toXML(component));
			deviceLinkService.saveDeviceLinkOptions(deviceLink);
			r.setObj(deviceLink);
		}
		catch (JSONException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return r;
	}
	/**
	 * 
	 * 
	 * @author max.zheng
	 * @create 2015-4-5下午11:13:19
	 * @modified by
	 * @param request
	 * @param deviceLinkId
	 * @return
	 */
	@RequestMapping(value="/deviceLink.do",params = "chooseDeviceLink")
	public ModelAndView chooseDeviceLink(HttpServletRequest request,String flag,String param) {
		if ("fromRoomConfig".equals(flag)) {
			request.setAttribute("selectUrl", "roomConfig.do?loadRoomConfigSelectDeviceLinks&roomType="+param);
			request.setAttribute("unSelectUrl", "roomConfig.do?loadRoomConfigUnSelectDeviceLinks&roomType="+param);
		}else if ("fromRoom".equals(flag)) {
			request.setAttribute("selectUrl", "room.do?loadRoomSelectDeviceLinks&roomId="+param);
			request.setAttribute("unSelectUrl", "room.do?loadRoomUnSelectDeviceLinks&roomId="+param);
		}
//		request.setAttribute("roomType", roomType);
		return new ModelAndView("hotel/deviceLink/chooseDeviceLinkComponent_ftl");
	}
	
	@RequestMapping(value="/deviceLink.do",params = "loadNodes")
	@ResponseBody
	public Map<String, Object> loadNodes(Pagination pg,String deviceLinkId) {
		Map<String, Object> result = new HashMap<String, Object>();
		int total = 0;
		List rows = new ArrayList();
		if (StringUtils.isNotBlank(deviceLinkId))
		{
//			DeviceLinkItem deviceLinkItem = deviceLinkService.loadDeviceLinkItem(Long.valueOf(deviceLinkId));
//			Component component = ComponentHandler.loadComponent(deviceLinkItem);
//			if (component!=null)
//			{
//				//转对应的节点
//				List<Node> nodes = component.getNodes();
//				total = nodes.size();
//				rows = nodes;	
//			}
		}
		result.put("total", total);
		result.put("rows", rows);	
		
		return result;
	}


}
